/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AdminController;

import DAO.AdminDAO;
import General.FoUtils;
import Config.Constants;
import General.XMLUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import product.generate.ProductList;
import product.generate.Products;
import user.generate.UserList;
import user.generate.Users;

/**
 *
 * @author NganNLK60334
 */
public class AdminController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ClassNotFoundException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String webPath = getServletContext().getRealPath("/");
            String xsdPath = webPath + "WEB-INF/classes/Schema/products.xsd";
            String xsdUserPath = webPath + "WEB-INF/classes/Schema/user.xsd";
            String filePath = webPath + "WEB-INF/Products.xml";
            String xmlUserPath = webPath + "WEB-INF/Users.xml";
            String action = request.getParameter("action");
            String currentPage = request.getParameter("current");

            if (action.equals("ProductsXmlCheck")) {
                Products proList = AdminDAO.getAllProducts();
                if (proList != null) {
                    XMLUtils.marshallClass(proList, filePath);
                    request.getRequestDispatcher(currentPage).forward(request, response);
                }
            } else if (action.equals("manageProduct")) {
                request.getRequestDispatcher(Constants.PAGE_MANAGE_PRODUCT).forward(request, response);
            } else if (action.equals("addProductLink")) {
                request.getRequestDispatcher(Constants.PAGE_ADD_PRODUCT).forward(request, response);
            } else if (action.equals("manageUserLink")) {
                request.getRequestDispatcher(Constants.PAGE_MANAGE_USER).forward(request, response);
            } else if (action.equals("ShowProduct")) {
                String proid = request.getParameter("proid");
                Object obj = XMLUtils.unmarshallClass(xsdPath, filePath, Products.class);
                if (obj != null && obj instanceof Products) {
                    Products proList = (Products) obj;
                    ProductList proType = null;
                    for (ProductList pt : proList.getProduct()) {
                        if (proid.equals(String.valueOf(pt.getProductID().intValue()))) {
                            proType = pt;
                            break;
                        }
                    }
                    if (proType != null) {
                        proType.setIsShow(!proType.isIsShow());
                    }

                    if (AdminDAO.updateStatusProduct(proType)) {
                        XMLUtils.marshallClass(proList, filePath);
                        Map<String, Object> params = new LinkedHashMap<String, Object>();
                        params.put("type", "productlist");
                        String result = XMLUtils.covertToString(webPath + "WEB-INF/Admin/manageProduct.xsl", filePath, params);
                        out.write(result);
                    }
                }

            } else if (action.equals("UsersXmlCheck")) {
                Users userList = AdminDAO.getAllUsers();
                if (userList != null) {
                    XMLUtils.marshallClass(userList, xmlUserPath);
                    request.getRequestDispatcher(currentPage).forward(request, response);
                }
//                String xmlPath = webPath + "WEB-INF/Users.xml";
//                 String username = request.getParameter("username");
//                Object obj = XMLUtils.unmarshallClass(xsdPath, filePath, Users.class);
//                if (obj != null && obj instanceof Products) {
//                    Users userList = (Users) obj;
//                    UserList userType = null;
//                    for (UserList ul : userList.getUser()) {
//                        if (username.equals(ul.getUsername())) {
//                            userType = ul;
//                            break;
//                        }
//                    }
//                    if (userType != null) {
//                        userType.setIsActive(!userType.isIsActive());
//                    }
//
//                    if (AdminDAO.updateStatusUser(userType)) {
//                        XMLUtils.marshallClass(userList, filePath);
//                        Map<String, Object> params = new LinkedHashMap<String, Object>();
//                        params.put("type", "userlist");
//                        String result = XMLUtils.covertToString(webPath + "WEB-INF/Admin/manageUser.xsl", xmlPath, params);
//                        out.write(result);
//                    }
//                }
//
            } else if (action.equals("SaveProduct")) {
                int productID = Integer.parseInt(request.getParameter("proId"));
                String productName = request.getParameter("proName");
                String price = request.getParameter("proPrice");
                String description = request.getParameter("proDes");
                int quantityInStock = Integer.parseInt(request.getParameter("proQuantity"));

                AdminDAO adao = new AdminDAO();
                boolean isDone = adao.updateProducts(productID, productName, price, description, quantityInStock);
                String context = getServletContext().getRealPath("/");
                Products proList = adao.getAllProducts();
                XMLUtils.marshallClass(proList, filePath);
                Map<String, Object> params = new LinkedHashMap<String, Object>();
                params.put("type", "productlist");
                String result = XMLUtils.covertToString(webPath + "WEB-INF/Admin/manageProduct.xsl", filePath, params);
                out.write(result);

            } else if (action.equals("addProducts")) {
                String productName = request.getParameter("txtname");
                int categoryID = Integer.parseInt(request.getParameter("selectCategory"));
                String price = request.getParameter("txtprice");
                String productImg = request.getParameter("file");
//                String option = request.getParameter("option");
                boolean isShow = true;
                int quantityInStock = Integer.parseInt(request.getParameter("txtQuantityInStock"));
                String description = request.getParameter("txtdescription");


                AdminDAO adao = new AdminDAO();
                int resultID = adao.insertProducts(productName, categoryID, price, productImg,
                        description, isShow, quantityInStock);
                if (resultID != -1) {
                    Products proList = adao.getAllProducts();
                    XMLUtils.marshallClass(proList, filePath);
                    request.getRequestDispatcher("/admin/manageProduct.jsp").forward(request, response);
                } else {
                    request.setAttribute("addSuccess", "Fail in add new product");
                }
            } else if (action.equals("createPDF")) {
                Date date = new Date();

                String productxml = webPath + "WEB-INF/Products.xml";
                String xslFilePath = webPath + "WEB-INF/Admin/listProductPDF.xsl";
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                StreamSource xmlFile = new StreamSource(new File(productxml));
                output = FoUtils.createFileFo(webPath, xsdPath, xsdPath, null, action);

                response.setContentType("application/pdf");
                byte[] content = output.toByteArray();
                response.setContentLength(content.length);
                // write to output
                response.addHeader("Content-Disposition",
                        "attachment; filename=" + "ListProduct_" + date + ".pdf");
                response.getOutputStream().write(content);
                response.getOutputStream().flush();
            } else if (action.equals("ShowUser")) {
                String username = request.getParameter("username");
                Object obj = XMLUtils.unmarshallClass(xsdUserPath, xmlUserPath, Users.class);
                if (obj != null && obj instanceof Users) {
                    Users userList = (Users) obj;
                    UserList userType = null;
                    for (UserList ul : userList.getUser()) {
                        if (username.equals(ul.getUsername())) {
                            userType = ul;
                            break;
                        }
                    }
                    if (userType != null) {
                        userType.setIsActive(!userType.isIsActive());
                    }

                    if (AdminDAO.updateStatusUser(userType)) {
                        XMLUtils.marshallClass(userList, xmlUserPath);
                        Map<String, Object> params = new LinkedHashMap<String, Object>();
                        params.put("type", "userList");
                        String result = XMLUtils.covertToString(webPath + "WEB-INF/Admin/manageUser.xsl", xmlUserPath, params);
                        out.write(result);
                    }
                }

            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TransformerException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SAXException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);

        } catch (SQLException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TransformerException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SAXException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);

        } catch (SQLException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
